
package org.sopt.dev.ImgKnight.monitor.nio;

import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.sopt.dev.ImgKnight.monitor.Monitor;


public class Peer {

	private Monitor monitor = null;
	
	private Channel channel = null;
	
	private ExecutorService nioBossExecutor = null;
	
	private ExecutorService nioWorkerExecutor = null;
	
	public Peer(Monitor monitor) {
		this.monitor = monitor;
	}
	
	public ChannelFuture open(SocketAddress peerAddress) {
		nioBossExecutor = Executors.newCachedThreadPool();
		nioWorkerExecutor = Executors.newCachedThreadPool();
		ChannelFactory factory 
			= new NioClientSocketChannelFactory(nioBossExecutor, nioWorkerExecutor);	
		ClientBootstrap bootstrap = new ClientBootstrap(factory);
		NioStringStreamHandler handler = new NioStringStreamHandler(monitor);
		bootstrap.getPipeline().addLast("handler", handler);
		bootstrap.setOption("tcpNoDelay", true);
		bootstrap.setOption("keepAlive", true);
		ChannelFuture future = bootstrap.connect(peerAddress);
		channel = future.awaitUninterruptibly().getChannel();
		return future;
	}
	
	public void close() {
		nioBossExecutor.shutdownNow();
		nioWorkerExecutor.shutdownNow();
		channel.close().awaitUninterruptibly();
	}
	
	public Channel getChannel() {
		return channel;
	}
	
	public String getIpAddress() {
		String address = channel.getRemoteAddress().toString();
		address = address.substring(1, address.indexOf(":"));
		return address;
	}
	
	public boolean isConnected() {
		return channel.isConnected();
	}
	
	public boolean equals(String peerAddress) {
		return (channel.getRemoteAddress().toString().equals(peerAddress)) ? true : false;
	}
}
